package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"fmt"
	"gorm_demo/model"
)

func main() {
	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	db.LogMode(true)
	//db.SetLogger(gorm.Logger{revel.TRACE})
	if err != nil {
		fmt.Println(err.Error())
	}
	if ok := db.HasTable(&model.User{}); ok {
		//simpleQuery(db)

		//plainQuery(db)

		StructMapQuery(db)
	}

	defer db.Close()
}

func StructMapQuery(db *gorm.DB) {
	// Struct
	user := model.User{}
	//var age = sql.NullInt64{12, false}
	//db.Where(&model.User{Name: "bbb", Age: age}).Find(&user)
	db.Where(&model.User{Name: "bbb", Age: 12}).Find(&user)
	fmt.Println("struct find ", user)

	user = model.User{}
	//age = sql.NullInt64{0, true}

	db.Where(&model.User{Name: "bbb", Age: 0}).Find(&user)
	fmt.Println("struct find ", user)

	//Map
	user = model.User{}
	db.Where(map[string]interface{}{"user_name": "bbb", "age": 12}).Find(&user)
	fmt.Println("map find ", user)

}

//繁琐的where查询
func plainQuery(db *gorm.DB) {
	//根据主键排序后查询第一个
	user := model.User{}
	db.Where("user_name=?", "bbb").First(&user)
	fmt.Println("Get first matched record ", &user)

	// Get all matched records
	users := make([] model.User, 10)
	db.Where("gender=?", "female").Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}

	//find not equal
	users = make([] model.User, 10)
	db.Where("user_name != ?", "bbb").Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}

	// IN
	users = make([] model.User, 10)
	db.Where("user_name in (?)", []string{"bbb", "cccc"}).Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}

	//LIKE
	users = make([] model.User, 10)
	db.Where("user_name like ?", "%ccc%").Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}

	//AND
	users = make([] model.User, 10)
	db.Where("user_name = ? and gender =?", "cccc", "female").Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}

}

//简单查询
func simpleQuery(db *gorm.DB) {
	//根据主键排序后查询第一个
	user := model.User{}
	db.First(&user)
	fmt.Println("the first", &user)

	//不做排序取第一个
	user = model.User{}
	db.Take(&user)
	fmt.Println("the take", &user)

	//主键倒叙排列后取第一个
	user = model.User{}
	db.Last(&user)
	fmt.Println("the last", &user)

	//查询所有
	users := make([]model.User, 2)
	db.Find(&users)
	for i, v := range users {
		fmt.Printf("find %d value is %v \n", i, v)
	}
	//根据主键查询
	user = model.User{}
	db.First(&user, 5)
	fmt.Println("the first with id", &user)
}
